<?php

namespace app\index\controller;

use think\Db;
use think\facade\Config;

class Admin extends \Common
{
/**
	 * 生成二维码
	 */
	public function getQrcode(){
        // 如果重新生成
        if (isset($_GET['new'])) {
            $tt = time();            
            // 生成二维码
            $qr_data  = $this->create_qrcode('http://admin.kireido.cn/daily_report/interface/index/middle/index?tt='.$tt,"./static/upload/qrcode/");
            $url = Config::get("ip") . "static/upload/qrcode/" . $qr_data["name"];
            $up = [
                "tt" => $tt,
                "url" => $url,
            ];
            Db::name("qrcode")->where("id", 1)->update($up);
        }else{ // 如果不是重新生成
            $url = Db::name("qrcode")->where("id", 1)->value('url');
        }        
        $this->Code(200, false, $url);
	}
	/**
	 * 生成二维码
	 * @param string $data      写入数据
	 * @param string $path      二维码保存路径
	 * @param string $ecc       错误修正水平    'L','M','Q','H'
	 * @param int    $size      二维码大小      1 - 10
	 */
	public function create_qrcode($data = '', $path = '', $ecc = 'H', $size = 10)
	{			
			$save_path = empty($path) ? \Env::get('root_path') . 'extend/qrcode/' : $path;
			include_once \Env::get('root_path') . 'extend/qrcode/qrlib.php';			
			if (!file_exists($save_path)) { mkdir($save_path); }			
			$filename = $save_path.'.png';			
			$errorCorrectionLevel = 'L';			
			if (isset($ecc) && in_array($ecc, array('L','M','Q','H'))) { $errorCorrectionLevel = $ecc; } 			
			$matrixPointSize = 4;			
			if (isset($size)) { $matrixPointSize = min(max((int)$size, 1), 10); }			
			if (isset($data)) {					
					if (trim($data) == '') {  exception("qrcode data cannot be empty"); }					
					$filename = $save_path.md5($data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';					
					\QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);					
			}else{					
					\QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
			}			
			$name = basename($filename);			
			$return_data['name'] = $name;
			$return_data['path'] = $save_path . $name;			
			return $return_data;			
	}
    
    # 获取ip白名单
    public function GetWhitelist()
    {
        $ipArr = Db::name("ip")->where("iid", 1)->find();
        $ip = empty($ipArr) ? "" : $ipArr["ip"];
        $remark = empty($ipArr) ? "" : $ipArr["remark"];
        $array = [
            "content" => $ip,
            "remark" => $remark
        ];
            $this->Code(200, false, $array);
    }

    # 设置ip白名单
    public function SetWhitelist()
    {
        if (isset($_POST["content"])) {
            $up = [
                "ip" => $_POST["content"],
                "remark" => $_POST["remark"] == "null" ? "" : $_POST["remark"]
            ];
            Db::name("ip")->where("iid", 1)->update($up);
            $this->Code(200, false, $_POST["content"]);
        }
    }

    public function getIp()
    {
        return $_SERVER['REMOTE_ADDR'];
    }

    # 生成token存储session
    private function MakeAndSave($admin)
    {
        if ($admin["role"] != 1) {

            $ip = Db::name("ip")->where("iid", 1)->find();
            $arr = explode("\n", $ip["ip"]);
            if ($admin["ip"] == 1 && !in_array($this->getIp(), $arr)) {
                $this->Code(403, "ip未在白名单");
            }

            $project = Db::name("distribution")
                ->alias("a")
                ->join("project b", "a.pid = b.pid")
                ->where("a.aid", $admin["aid"])
                ->select();
            $url = [];
            foreach ($project as $value) {
                $url[] = $value["url"];
            }

            # 存储session
            $_SESSION["admin" . $admin["aid"]] = $url;
        }

        $adminInfo = [
            "aid"  => $admin["aid"],
            "role" => $admin["role"],
            "time" => time()
        ];
        $data = [
            "roles" => $admin["role"] == 1 ? ["super"] : ["admin"],
            "token" => $this->MakeToken($adminInfo),
            "currentAuthority" => $admin["role"] == 1 ? "admin" : "user"
        ];

        return $data;
    }

    # 微信登录
    public function WxLogin()
    {
        if (isset($_POST["code"])) {
            $getAccessToken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->secret . "&code=" . $_POST["code"] . "&grant_type=authorization_code";
            $accessToken = $this->GetCurl($getAccessToken);
            if (isset($accessToken["access_token"]) && isset($accessToken["openid"])) {
                $admin = Db::name("admin")
                    ->where("openid", $accessToken["openid"])
                    ->find();
                // 记录登录ip时间
                $log = [
                    "aid" => $admin["aid"],
                    "name" => $admin["name"],
                    "sys" => '每日报表',
                    "ip" => request()->ip(),
                    "time" => date('Y-m-d H:i:s')
                ];
                $getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $accessToken["access_token"] . "&openid=" . $accessToken["openid"];
                if (isset($this->token["aid"])) {
                    $getUserInfo = $this->GetCurl($getUserInfo);
                    if (!isset($getUserInfo["errcode"])) {
                        $userInfo = [
                            "openid" => $accessToken["openid"],
                            "avatar" => $getUserInfo["headimgurl"]
                        ];
                        if (!empty($admin)) {
                            $this->Code(40003, "微信已经被绑定,请核对");
                        } else {
                            $this->addLoginLog($log); // 登录日志
                            Db::name("admin")->where("aid", $this->token["aid"])->update($userInfo);
                            $admin = Db::name("admin")->where("aid", $this->token["aid"])->find();
                            $data = $this->MakeAndSave($admin);
                            $this->Code(200, "绑定成功", $data);
                        }
                    } else {
                        $this->Code(40003, "綁定失败,稍后再试");
                    }
                } else {
                    if (!empty($admin)) {
                        $this->addLoginLog($log); // 登录日志
                        $data = $this->MakeAndSave($admin);
                        $this->Code(200, false, $data);
                    } else {
                        $this->Code(40003, "您的微信尚未绑定账户");
                    }
                }
            } else {
                $this->Code(40003, 403);
            }
        } else {
            $this->Code(40003, 403);
        }
    }

    # 登录
    public function Login()
    {
        if (isset($_POST["username"]) && isset($_POST["password"])) {
            $username = $_POST["username"];
            $password = $_POST["password"];
            $admin = Db::name("admin")
                ->where("username", $username)
                ->find();
            if (!empty($admin)) {
                if ($password == $admin["password"]) {
                    // 记录登录ip时间
                    $log = [
                        "aid" => $admin["aid"],
                        "name" => $admin["name"],
                        "sys" => '每日报表',
                        "ip" => request()->ip(),
                        "time" => date('Y-m-d H:i:s')
                    ];
                    $this->addLoginLog($log);

                    $data = $this->MakeAndSave($admin);
                    $this->Code(200, false, $data);
                } else {
                    $this->Code(403, "密码错误");
                }
            } else {
                $this->Code(403, "账号不存在,请核对");
            }
        } else {
            $this->Code(403, 403);
        }
    }
    # 添加登录日志
    private function addLoginLog($log)
    {
        Db::table("merge.m_admin_log")->insert($log);
    }
    # 添加登录日志-古董
    public function addLoginLogDepots()
    {
        $data = input('post.');
        // 验证token
        if($data['token_depots'] == md5($data['name'].'abc&3%1-')){
            unset($data['token_depots']);
            Db::table("merge.m_admin_log")->insert($data);
            $rs = ['操作成功',1];
            return json_encode($rs);
        }
        
    }
    # 登录日志列表
    public function getLoginLogs()
    {
        if (input("page") && input("limit")) {
            $notion = Db::table("merge.m_admin_log")
                // ->alias("l")
                // ->leftJoin("merge.m_admin a", "a.aid = l.aid")
                ->page(input("page", 1), input("limit", 10))
                // ->field("l.*,a.name as name2")
                ->order("id desc")
                ->select();
            $total = Db::table("merge.m_admin_log")->count();
            $data = [
                "list" => $notion,
                "total" => $total
            ];
            $this->Code(200, false, $data);
        }
    }

    # 获取用户信息
    public function Info()
    {
        $aid = $this->token["aid"];
        $local = $_SERVER["HTTP_REFERER"];
        $a = explode("?", $local);
        $string = $a[0];
        $b = explode(Config::get("app.url"), $string);
        $bb = explode("/", $b[1]);
        if ($bb[0] != "") {
            $local = Config::get("app.url") . $bb[0] . "/";
        }
        $admin = Db::name("admin")
            ->where("aid", $aid)
            ->find();
        if ($admin["role"] == 1) {
            $all = Db::name("import")->count();
            $destineNum = Db::name("import")->where("state", 1)->count();
            $doNum = Db::name("import")->where("state", 2)->count();
            $completeNum = Db::name("import")->where("state", 3)->count();
        } else {
            $all = Db::name("import")->count();
            $destineNum = Db::name("import")->where("pid", $aid)->where("state", 1)->count();
            $doNum = Db::name("import")->where("pid", $aid)->where("state", 2)->count();
            $completeNum = Db::name("import")->where("pid", $aid)->where("state", 3)->count();
        }
        if ($admin["role"] == 1) {
            $project = Db::name("project")
                ->select();
            $url = [];
            $url[] = [
                "id"   => 0,
                "name" => "超级管理后台",
                "url"  => Config::get("app.url")
            ];
            foreach ($project as $value) {
                $url[] = [
                    "id"   => $value["pid"],
                    "name" => $value["name"],
                    "url"  => $value["url"],
                ];
            }
            $data = [
                "roles"        => ["super"],
                "avatar"       => $admin["avatar"] == "" ? Config::get("app.ip") . "static/image/admin.jpg" : $admin["avatar"],
                "name"         => $admin["name"],
                "username"     => $admin["username"],
                "isSuperAdmin" => true,
                "myPro"        => $url,
                "isBindWx"     => $admin["openid"] != "",
                "matterCount"  => [$all, $destineNum, $doNum, $completeNum]
            ];
        } else {
            $project = Db::name("distribution")
                ->alias("a")
                ->join("project b", "a.pid = b.pid")
                ->where("a.aid", $aid)
                ->order("b.pid = 15, b.pid desc")
                ->select();
            $url = [];
            $myPro = [];
            foreach ($project as $value) {
                if ($value["pid"] == 15) {
                    array_unshift($myPro, [
                        "id"   => $value["pid"],
                        "name" => $value["name"],
                        "url"  => $value["url"],
                    ]);
                } else {
                    $myPro[] = [
                        "id"   => $value["pid"],
                        "name" => $value["name"],
                        "url"  => $value["url"],
                    ];
                }
                $url[] = $value["url"];
            }

            $_SESSION["admin" . $aid] = $url;
            if ((!in_array($local, $_SESSION["admin" . $aid]) && $local != Config::get("app.url") . "login/") && (!in_array($local, $_SESSION["admin" . $aid]) && $local != Config::get("app.url"))) {
                $this->Code(801, "非法身份登录");
            }

            $data = [
                "roles"        => ["admin"],
                "avatar"       => $admin["avatar"] == "" ? Config::get("app.ip") . "static/image/admin.jpg" : $admin["avatar"],
                "name"         => $admin["name"],
                "username"     => $admin["username"],
                "isSuperAdmin" => false,
                "myPro"        => $myPro,
                "isBindWx"     => $admin["openid"] != "",
                "matterCount"  => [$all, $destineNum, $doNum, $completeNum]
            ];
        }

        $this->Code(200, false, $data);
    }

    # 注销
    public function logout()
    {
        $aid = $this->token["aid"];
        if (isset($_SESSION["admin" . $aid])) {
            unset($_SESSION["admin" . $aid]);
        }
        $this->Code(200, false, "success");
    }
}
